/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2020年10月31日
*   描    述：
*   
* ================================================================*/


#include <iostream>
#include <vector>
using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution{
public:
    vector<int> res;
    int targetK;

    vector<int> distanceK(TreeNode *root, TreeNode *target, int K){
        targetK = K;
        dfs(root, target);

        return res;
    }

    int dfs(TreeNode *root, TreeNode *target){
        if(root == NULL){
            return -1;
        }

        if(root == target){
            subtree_add(root, 0);
            return 1;
        }

        int left = dfs(root->left, target);
        if(left != -1){
            if(targetK == left){
                res.push_back(root->val);
                return -1;
            }

            subtree_add(root->right, left + 1);
            return left + 1;
        }

        int right = dfs(root->right, target);
        if(right != -1){
            if(targetK == right){
                res.push_back(root->val);
                return -1;
            }

            subtree_add(root->left, right + 1);
            return right + 1;
        }

        return -1;
    }

    void subtree_add(TreeNode *root, int K){
        if(root == NULL){
            return;
        }

        if(K == targetK){
            res.push_back(root->val);
        }else{
            subtree_add(root->left, K + 1);
            subtree_add(root->right, K + 1);
        }
    }
};